package logic

import (
	"fmt"
	"gitee.com/kristas/booting-go/gen_tool/booctl/creator"
	"gitee.com/kristas/booting-go/gen_tool/booctl/util"
	"os"
	"path"
)

func InitHandler(pkgName string, args []string) error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	if len(args) > 0 {
		wd = fmt.Sprintf("%s/%s", wd, args[0])
	}
	if err = util.MkDir(wd); err != nil {
		return err
	}
	if err := os.Chdir(wd); err != nil {
		return err
	}
	var cmd util.GoCmd
	if !util.FileExist("go.mod") {
		cmd.ModInit(pkgName)
	}

	err = creator.NewBatchCreator(
		creator.NewGoFile("main", "", "", true),
		&creator.UsePluginFile{
			FileName: "use_logrus",
			Paths: Arr{
				"gitee.com/kristas/booting-go/framework",
				"gitee.com/kristas/booting-go/plugin/logrus_plugin",
			},
			Plugins:    Arr{"logrus_plugin.NewLoggerFactory()"},
			Processors: nil,
		},
		&creator.ConfigFile{
			Config: creator.Properties{
				"application.app_name":           path.Base(pkgName),
				"application.logging.adapter":    "logrus-log",
				"application.logging.skip_index": 4,
				"application.time_format":        "2006-01-02 15:04:05",
				"application.web.charset":        "UTF-8",
			},
		},
		&creator.ConfigFile{
			Env: "local",
			Config: creator.Properties{
				"application.environment":   "local",
				"application.logging.level": "debug",
				"server.port":               8000,
			},
		},
		&creator.ConfigFile{
			Env: "prod",
			Config: creator.Properties{
				"application.environment":   "prod",
				"application.logging.level": "warn",
				"server.port":               80,
			},
		},
	).Create()
	if err != nil {
		return err
	}
	defer cmd.FmtAll("init", path.Base(pkgName))
	return nil
}
